from django.middleware import http
from django import http
from django.views import View
import json
from django_redis import get_redis_connection
from verifications.libs.captcha.captcha import captcha
from verifications.libs.yuntongxun.ccp_sms import CCP
import random

from users.views import logger

from celery_tasks.sms.tasks import ccp_send_sms_code


class ImageCodeView(View):
    """图形验证码
     GET http://www.meiduo.site:8000/image_codes/550e8400-e29b-41d4-a716-446655440000/
    """
    def get(self,request,uuid):
        """
        实现图形验证码逻辑
        :param uuid: UUID
        :return: iamge/jpg
        """
        #生成图形验证码
        text,image =captcha.generate_captcha()
        #使用配置的redis数据库的别名,创建连接到redis的对象
        redis_conn = get_redis_connection('verify_code')
        #使用连接到redis的对象去操作数据存储到redis
        #图形验证码必须要有有效期,美多设置300秒
        #                  key       过期时间  value
        redis_conn.setex('img_%s' % uuid,300,text)


        #响应图形验证码:image/jpg
        return http.HttpResponse(image,content_type='image/jpg')


class SMSCodeView(View):
    """短信验证码"""
    def get(self, request, mobile):
        """

        :param request:请求对象
        :param mobile: 手机号
        :return: JSON
        """
        #1.接收参数
        image_code_client = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')

        #校验参数
        if not all([image_code_client,uuid]):
            return http.JsonResponse({
                'code':400,
                'errmsg':'缺少必传参数'
            },status=400)

        #3.创建连接到redis的对象
        redis_conn = get_redis_connection('verify_code')

        #4.提取图形验证码
        image_code_server =redis_conn.get('img_%s' % uuid)
        if image_code_server is None:
            #图形验证码过期或者不存在
            return http.JsonResponse({
                'code':400,
                'errmsg':'图形验证码失效'
            },status=400)

        #5.删除图形验证码,避免恶意测试图形验证码
        try:
            redis_conn.delete('img_%s' % uuid)

        except Exception as e:
            logger.error()

        # 6. 对比图形验证码
        #bytes转字符串
        image_code_server = image_code_server.decode()
        #转小写比较
        if image_code_client.lower() != image_code_server.lower():
            return http.JsonResponse({
                'code':400,
                'errmsg':'输入图形验证码错误'
            },status=400)

        #链接redis数据库:
        redis_conn = get_redis_connection('verify_code')
        #从redis数据库中获取存入的数据
        send_flag = redis_conn.get('send_flag_%s'% mobile)
        if send_flag:
            return http.JsonResponse({
                'code':400,
                'errmsg':'发送短信过于频繁'
            })

        #7.生成短信验证码,生成6位数验证码
        sms_code = '%06d' % random.randint(0,999999)
        logger.info(sms_code)

        #8. 保存短信验证码
        #短信验证码有效期,300s
        # redis_conn.setex('sms_%s' % mobile,300,sms_code)
        # #往redis中存入数据,key值和value值随意指定,但时间必须为60s
        # #
        # redis_conn.setex('send_flag_%s'%mobile,60,1)



        #9.发送短信验证码
        # 短信模板
        # #旧
        # CCP().send_template_sms(mobile,[sms_code,5],1)
        #用异步的方式发送短信-发布任务
        ccp_send_sms_code.delay(mobile,sms_code)
        print('短信验证码',sms_code)
        # 创建Redis 管道
        p1 = redis_conn.pipeline()

        # 1.将Redis请求添加到队列
        p1.setex('sms_%s' % mobile, 300, sms_code)
        p1.setex('send_flag_%s' % mobile, 60, 1)

        # 执行请求,这一步千万别忘了
        p1.execute()


        return http.JsonResponse({
            'code':0,
            'errmsg':'发送短信成功'
        })




